<template>
  <view class="checkbox-group">
    <view v-if="title" class="checkbox-group__header">
      <view class="title">
        {{ title }}
      </view>
    </view>
    <slot />
  </view>
</template>

<script lang="ts">
import { defineComponent, provide, watch, inject } from '@vue/composition-api'
import { showToast } from '@/hooks'

export default defineComponent({
  props: {
    value: {
      type: Array,
      default: () => [0],
    },
    textPosition: {
      type: String,
      default: 'right',
    },
    size: {
      type: String,
      default: 'md',
    },
    title: {
      type: String,
      default: '',
    },
    limit: {
      type: Number,
      default: Infinity,
    },
    limitToast: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    contentDisabled: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['change'],
  setup(props, { emit }) {
    const formItem: any = inject('formItem', null)
    const checkboxList: any[] = []
    const checkAll = () => {
      const labels = checkboxList.filter((x) => !x.disabled).map((x) => x.label)

      emit('input', labels)
    }
    provide('checkboxParent', {
      checkboxList,
      textPosition: props.textPosition,
      size: props.size,
      disabled: props.disabled,
      contentDisabled: props.contentDisabled,
      addCheckbox(checkbox) {
        checkboxList.push(checkbox)
        // init
        checkbox.vm.setCheck(checkbox.label, props.value)
      },
      removeCheckbox(label) {
        const index = checkboxList.findIndex((x) => x.label === label)

        checkboxList.splice(index, 1)
      },
      checkboxClick(label) {
        const value = props.value
        const labelIndex = value.findIndex((x) => x === label)
        if (labelIndex === -1) {
          if (props.value.length >= props.limit) {
            showToast({
              title: props.limitToast.replace(/{num}/g, props.limit + ''),
            })
            return false
          }
          value.push(label)
        } else {
          value.splice(labelIndex, 1)
        }

        emit('input', value)
      },
    })

    watch(
      () => props.value,
      (newVal) => {
        checkboxList.forEach((checkbox) => {
          checkbox.vm.setCheck(checkbox.label, newVal)
        })
        emit('change', newVal)
        if (formItem && formItem.validate) {
          formItem && formItem.validate()
        }
      }
    )

    return {
      checkAll,
    }
  },
})
</script>
<style lang="scss" scoped>
.checkbox-group {
  width: 100%;
  &__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24rpx;
  }
  .title {
    font-weight: bold;
    color: $--font-primary-c;
    font-size: 28rpx;
  }
}
</style>
